package com.euq.service.Impl;

import com.euq.entity.Dict;
import com.euq.dto.Ret;
import com.euq.mapper.DictMapper;
import com.euq.service.DictService;
import com.euq.utils.AddDictItems;
import com.euq.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DictServiceImpl implements DictService {
    @Autowired
    private DictMapper dictMapper;

    @Override
    public Object list() {
        return Ret.success(dictMapper.list());
    }

    @Override
    public void deleteById(int id) {
        long pid = id;
        dictMapper.deleteByPid(pid);
        dictMapper.deleteById(id);
    }

    @Override
    public void addDict(String dictName, String value) {
        Dict dict = dictMapper.findByNameAndPid(dictName, 0L);
        if (dict == null) {
            dict = new Dict();
            dict.setName(dictName);
            dict.setTips(dictName + " 字典");
            dict.setNum("0");
            dict.setPid(0L);
            dictMapper.insertDict(dict);
        }
        List<Dict> items = AddDictItems.parseDictItems(value, dict.getId());
        for (Dict item : items) {
            dictMapper.insertDict(item);}
    }

    @Override
    public void update(Long id, String dictName, String value) {
        try{
            if(BeanUtils.isOneEmpty(id,dictName)){
                throw new Exception("参数不能为空");
            }
            dictMapper.deleteByPid(id);
            addDict(dictName,value);
        }catch(Exception e){throw new RuntimeException("修改字典信息失败",e);
        }

    }

    @Override
    public Dict getDictByName(String name) {
        dictMapper.getDictByName(name);
        return null;
    }
}
